package top.byteio.common.message.messager;

import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import top.byteio.common.message.client.MailMessageHelper;
import top.byteio.common.message.client.MessagerHelper;
import top.byteio.common.message.eunms.Subtype;
import top.byteio.common.message.pojo.MessagerProperty;
import top.byteio.common.message.pojo.Notice;

@Slf4j
@Setter
public class MailMessager implements NoticeMessager {

    // 使用volatile关键字确保多线程环境下的可见性
    private static volatile MailMessager instance;

    private final MessagerProperty property;

    private MailMessager(MessagerProperty property) {
        this.property = property;
    }

    public static MailMessager getInstance(MessagerProperty property) {
        if (instance == null) {
            synchronized (MailMessager.class) {
                if (instance == null) {
                    instance = new MailMessager(property);
                }
            }
        }
        return instance;
    }

    /**
     * 发送HTML格式邮件
     * @param notice 通知内容
     * @return true:发送成功 false:发送失败
     * @author lerryxia
     */
    @Override
    public boolean send(Notice notice) {
        MimeMessage message = helper().getHelper(property);
        try {
            message.setFrom(new InternetAddress(property.getUsername())); // 发件人
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(notice.getTo())); // 收件人
            message.setSubject(notice.getSubject()); // 主题
            String subtype;
            if (notice.getSubtype() == null) notice.setSubtype(Subtype.TEXT);
            subtype = notice.getSubtype().getSubtype() + "; charset=" + property.getEncoding();
            message.setContent(notice.getContent(), subtype); // 内容
            // 发送邮件
            Transport.send(message);
            log.info("发送HTML邮件成功: {}", notice);
            return true;
        } catch (MessagingException e) {
            log.error("发送HTML邮件失败: 通知{},异常={}", notice, e.getMessage());
            return false;
        }
    }

    @Override
    public MessagerHelper<MimeMessage> helper() {
        return new MailMessageHelper();
    }

}
